const express = require("express");
const { getToken, verify } = require("../utils");
const pool = require("../pool.js");

const cartRouter = express.Router();
module.exports = cartRouter;

// 根据用户uid查找购物车数据
cartRouter.get("/find", (req, res, next) => {
  let token = req.header("authorization");
  let uid;
  verify(token, (msg) => (uid = msg.uid));
  var sql = `select * from cart where uid=?`;
  pool.query(sql, [uid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: 200, data: r });
  });
});
// 添加购物车数据
cartRouter.post("/insert", (req, res, next) => {
  var uid = req.body.uid;
  var pname = req.body.pname;
  var cprice = req.body.cprice;
  var sql = `select uid from user where uid=?`;
  pool.query(sql, [uid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      sql = `insert into cart values(null,?,?,?)`;
      pool.query(sql, [uid, pname, cprice], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        if (r.affectedRows != 0) {
          res.send({ code: 200, msg: "插入数据成功" });
        } else {
          res.send({ code: 201, msg: "插入失败" });
        }
      });
    } else {
      res.send({ code: 202, msg: "找不到用户账号" });
    }
  });
});
// 根据用户账号和商品名称删除数据
cartRouter.delete("/delete", (req, res, next) => {
  var uname = req.query.uname;
  var pname = req.query.pname;
  var sql = `delete from cart where uname=? and pname=?`;
  pool.query(sql, [uname, pname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) {
      res.send({ code: 201, msg: "数据不存在" });
    } else {
      res.send({ code: 200, msg: "删除成功" });
    }
  });
});
